﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using BackEnd.Common;
using BackEnd.Models;
using BusinessLayer.FindArtInfo;
using BusinessLayer.RegInfo;
using BusinessLayer.RegInfo.Entities;
using BusinessLayer.RegInfo.Models;
using CommandLib;
using Constants = BackEnd.Common.Constants;

namespace BackEnd.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        public JsonResult Search(string firstName, string lastName, string email, int? countryId, int? status, int? partnerId, DateTime? fromDate, DateTime? toDate, int? typePay, int pageIndex, int pageSize)
        {
            int totalRecord;
            List<AccountExtend> listAccount = new AccountBL().Search(firstName, lastName, email, countryId, status, partnerId, fromDate, toDate, typePay, pageIndex, pageSize, out totalRecord);
            ListObjectModel<AccountExtend> listObject = new ListObjectModel<AccountExtend>
            {
                ListItem = listAccount,
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecord = totalRecord
            };
            return Json(listObject, JsonRequestBehavior.AllowGet);
        }

        public AccountModel InitAccountEditModel(int accountId)
        {
            Account account = new AccountBL().GetById(accountId);
            AccountModel model = new AccountModel();
            model.CountryId = account.CountryId;
            model.CreateDate = account.CreateDate;
            model.Email = account.Email;
            model.EndDate = account.EndDate;
            model.FirstName = account.FirstName;
            model.LastName = account.LastName;
            model.ListCountry = new BusinessLayer.RegInfo.CountryBL().GetAll();
            model.PassWord = account.PassWord;
            model.StartDate = account.StartDate;
            model.Status = account.Status;
            model.Id = account.Id;
            DateTime dateTimeNow = new CommonBL().GetDateTimeNow();
            if (account.EndDate != null && account.StartDate != null)
            {
                TimeSpan timeSpan = Convert.ToDateTime(account.EndDate) - dateTimeNow;
                model.CurrentExpiresDate = timeSpan.Days;
            }
            return model;
        }

        [CustomAuthorize(Action = Constants.AdminActions.EditAccount)]
        public ActionResult Edit(int accountId)
        {
            return View(InitAccountEditModel(accountId));
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.EditAccount)]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(AccountModel model)
        {
            Account account = new AccountBL().GetByEmail(model.Email);
            if(account != null && account.Id != model.Id)
            {
                ModelState.AddModelError("MessageResult", "Email already exists!");
            }
            if (ModelState.IsValid)
            {
                account = new AccountBL().GetById(model.Id);
                account.FirstName = model.FirstName;
                account.LastName = model.LastName;
                account.CountryId = model.CountryId;
                account.CreateDate = model.CreateDate;
                account.Email = model.Email;                
                account.Status = model.Status;
                new AccountBL().Update(account, model.ExpiresDate);
                if (model.ConfirmSendEmail)
                {
                    //send email
                    string subject = "Access to FindArtInfo.com";
                    string content = string.Format("Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password. You would run the risk of disabling your account if any invalid login.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>", account.LastName, account.Email, account.PassWord);
                    Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, account.Email,
                                            account.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
                    //end
                }
                ModelState.AddModelError("MessageResult", "Update success");
                return View(InitAccountEditModel(model.Id));
            }
            else
            {
                //ModelState.AddModelError("MessageResult", "Error");
                return View(InitAccountEditModel(model.Id));   
            }
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.DeleteAccount)]
        public JsonResult Delete(string listId)
        {
            AccountBL accountBl = new AccountBL();
            string[] arrayId = listId.Split('_');
            for (int i = 0; i < arrayId.Length; i++)
            {
                accountBl.Delete(Convert.ToInt32(arrayId[i]));
            }
            return Json("Success", JsonRequestBehavior.AllowGet);
        }

        public ActionResult ResetPassword(int accountId)
        {
            return View(InitAccountEditModel(accountId));
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.EditAccount)]
        [ValidateAntiForgeryToken]
        public ActionResult ResetPassword(AccountModel model)
        {
            Account account = new AccountBL().GetById(model.Id);
            account.PassWord = model.PassWord;
            new AccountBL().Update(account);
            if(model.ConfirmSendEmail)
            {
                //send email
                string subject = "Access to FindArtInfo.com";
                string content = string.Format("Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password. You would run the risk of disabling your account if any invalid login.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>", account.LastName, account.Email, account.PassWord);
                Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, account.Email,
                                        account.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
                //end
            }
            ModelState.AddModelError("MessageResult", "Update success");
            return View(InitAccountEditModel(model.Id));
        }

        public ActionResult BlackList()
        {
            return View();
        }  

        [HttpPost]
        public JsonResult InsertBlackList(string listEmail)
        {
            AccountBL accountBl = new AccountBL();
            string[] arrayEmail = listEmail.Split(new string[] { "#####" }, StringSplitOptions.None);
            for (int i = 0; i < arrayEmail.Length; i++)
            {
                accountBl.InsertBlackList(arrayEmail[i]);
            }
            return Json("Success", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult SearchBlackList(string email, int pageIndex, int pageSize)
        {
            int totalRecord;
            List<AccountExtend> listAccount = new AccountBL().SearchBlackList(email, pageIndex, pageSize, out totalRecord);
            ListObjectModel<AccountExtend> listObject = new ListObjectModel<AccountExtend>
            {
                ListItem = listAccount,
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecord = totalRecord
            };
            return Json(listObject, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DeleteBlackList(string listId)
        {
            AccountBL accountBl = new AccountBL();
            string[] arrayId = listId.Split('_');
            for (int i = 0; i < arrayId.Length; i++)
            {
                accountBl.DeleteBlackList(Convert.ToInt32(arrayId[i]));
            }
            return Json("Success", JsonRequestBehavior.AllowGet);
        }
        
    }
}
